package com.zhouyu.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
@Conditional(MyCondition.class)
public class UserService implements UserInterface, ApplicationContextAware, BeanNameAware, InitializingBean {

	@Resource
	private OrderService orderService;
	private UserService userService;
	@Value("jack")
	private User user;

	@Override
	public void test() {
		System.out.println(UserService.class.getSimpleName() + " test " + orderService);
	}

	public void testUser() {
		System.out.println(UserService.class.getSimpleName() + " testUser " + user);
	}

	@Transactional
	public void testTransactional1() {
		System.out.println("testTransactional1");
		userService.testTransactional2();
	}


	@Transactional(propagation = Propagation.NEVER)
	public void testTransactional2() {
		System.out.println("testTransactional2");
	}


	public UserService() {
		System.out.println("### 实例化1");
	}

	@Autowired
	public UserService(String bbbb) {
		System.out.println("### 实例化2: " + bbbb);
	}

	@Autowired
	public void setUserService(UserService userService) {
		System.out.println("### 依赖注入 @Autowired");
		this.userService = userService;
		System.out.println("setUserService " + userService + " orderService " + orderService);
	}

	@Override
	public void setBeanName(String name) {
		System.out.println("### Aware回调 BeanNameAware");
		System.out.println("setBeanName " + name);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		System.out.println("### Aware回调 ApplicationContextAware");
	}

	@PostConstruct
	public void init() {
		System.out.println("### 初始化前 @PostConstruct");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("### 初始化 InitializingBean.afterPropertiesSet()");
	}

	@PreDestroy
	public void destroy() {
		System.out.println("### 销毁前 @PreDestroy");
	}

}
